import json
import pickle
import time
import zipfile
import os
import numpy

import ai.base_agent
from ai.infer_paras import *
from ai.map import *


scenario_id = "2201010110"
map_id = "221"
with open("data/scenarios/"+scenario_id+".json") as f:
    scenario_data = json.load(f)
with open("data/maps/map_"+map_id+"/basic.json") as f:
    basic_data = json.load(f)
with open("data/maps/map_"+map_id+"/cost.pickle", 'rb') as file:
    cost_data = pickle.load(file)
see_data = numpy.load("data/maps/map_"+map_id+"/"+map_id+"see.npz")['data']

my_map = Map(basic_data, cost_data, see_data)
observation = scenario_data
observation['jm_points'] = [{'pos': 4239}, {'pos': 4339}, {'pos': 4242}, {'pos': 4240}]
bop = observation['operators'][5]
bop['cur_hex'] = 4240

neighbors = list(my_map.get_grid_distance(bop['cur_hex'], 0, 3))
tar_hex_list = []
for jm_point in observation['jm_points']:  # 遍历间瞄点信息
    for neighbor in neighbors:
        if jm_point['pos'] == neighbor:
            neighbors.remove(neighbor)
            continue
for neighbor in neighbors:
    if my_map.get_grid_type(neighbor) == 1 or my_map.get_grid_type(neighbor) == 2:  # 如果周围有从林地或居民地
        tar_hex_list.append(neighbor)
if tar_hex_list:
    map_distance_list = [my_map.get_distance(i, bop['cur_hex']) for i in tar_hex_list]  # 邻域坐标与夺控点坐标的距离列表
    b = map_distance_list.index(min(map_distance_list))  # 邻域距离坐标中的最小值的索引
    tar_hex = tar_hex_list[b]
else:
    distances = [my_map.get_distance(i, bop['cur_hex']) for i in neighbors]
    ind = distances.index(min(distances))
    tar_hex = neighbors[ind]
print(tar_hex)